
#ifndef _HID_PROX_H_
#define _HID_PROX_H_
#include <BitBuf.h>
#include "rfid_interface.h"
#include <Utility/BitSlider.h>

/*------------------------------------------------------------*/
#define FSK_FC_Period		(RFID_ITF_COLLECT_FREQ/125000)
#define FSK_High_Num		8
#define FSK_Low_Num			10
#define FSK_Long_Period		(FSK_Low_Num * FSK_FC_Period)
#define FSK_Short_Period	(FSK_High_Num * FSK_FC_Period)


#define DECODE_MAX(a, b)	(((a) > (b)) ? (a) : (b))
#define DECODE_MIN(a, b)	(((a) < (b))? (a) : (b))
//点
typedef struct {
	uint32_t position;	//采样位置
	uint16_t value;		//采样值
}Piont_T;

typedef struct {
	uint8_t levelNum;		//期望接收的长度
	uint8_t lowNum;			//低电平位宽
	uint8_t highNum;		//高电平位宽
	uint8_t longPeriodRange[2];		//低频有效范围
	uint8_t shortPeriodRange[2];	//高频有效范围
	uint8_t header_init;	//sof初始值
	uint8_t periodShort;	//短周期
	uint8_t periodLong;		//长周期
	uint8_t sync;			//sof值
}HIDProxDecoderParams_T;



//HID卡的数据分析
//周期65us属于高频 bit = 0 持续时间380us 周期次数6
//周期80us属于低频 bit = 1 持续时间400us 周期次数5
//总共96个bit
//引导头为0x1D (前面抛弃10个bit再检测,数据复制两串,保证引导头能够拼接起来)
//数据按照曼切斯特编码再解析一遍 总共88个电平位 44个数据位 5.5个字节


#define HID_CARD_PT_BUF_SIZE				RFID_ITF_DMA_BUF_LEN / 2 / 8
#define HID_CARD_BIT_BUF_SIZE				HID_CARD_PT_BUF_SIZE / 4
#define HID_CARD_HEADER_VALUE				0x1D

#define HID_CARD_SOF						0xB8			//高位在前

#define HID_CARD_SHORT_FRAME_SIZE				96
#define HID_CARD_LONG_FRAME_SIZE				(HID_CARD_SHORT_FRAME_SIZE * 2)

enum HidFrameType{
	HID_FRAME_None,
	HID_FRAME_Short,
	HID_FRAME_Long,
};

typedef struct {
	enum HidFrameType type;
	BitSlider_T* bits;
}HidFrame_T;


typedef struct {
	uint8_t type;
	uint8_t ulen;
	uint8_t uid[16];
}HidProxTag_T;

#if 0
typedef struct{
	HIDProxDecoder_T decoder;
	HidFrame_T frameBackup;
	HidFrame_T frameInput;
	BitSlider_T receive;
	uint32_t receiveBuffer[16];
	BitSlider_T input;
	uint32_t inputBuffer[16];
	BitSlider_T output;
	uint32_t outputBuffer[16];
	uint8_t done;
}HIDProx_T;
#endif 
///
typedef struct {
//	解码缓冲区
	uint32_t count;			//已解析的采样数
	Piont_T troughs[2];		//波谷
	uint8_t curTrough;		//当前波谷
	uint16_t cursor;		//当前波以解码点
	uint8_t state;			//起始标志
	uint8_t periodBuf[128];	//周期缓存
	uint8_t periodCount;	//周期计数
	uint8_t prevPeriod;		//缓存之前的周期
	uint8_t highCount;		//高频计数
	uint8_t lowCount;		//低频计数
	uint8_t header;			//起始标识缓存
	const HIDProxDecoderParams_T* param;
	
	HidFrame_T frameBackup;
//		HidFrame_T frameInput;
	BitSlider_T* receive;
	BitSlider_T* input;
//		BitSlider_T* output;
//		uint8_t done;
}HIDProxDecoder_T;


void HIDProx_Init(void);

void HIDProx_Reset(void);

int HIDProx_Read(HidProxTag_T* tag);

void HIDProxDecoder_Input(const uint16_t* data, uint16_t length);

void HIDProx_Complete(BitSlider_T* receive);

#endif

